package com.zdp.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author sesshomaru
 * @date 2019/11/25 22:29
 */
@Component
public class RabbitConsumer{

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue001",durable = "true"),
            exchange = @Exchange(value = "exchange001",durable = "true",type = "topic",ignoreDeclarationExceptions = "true"),
            key = "springboot.#"
            ))
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws IOException {
        System.out.println("-------消费端------");
        System.out.println("消费端Payload: "+ message.getPayload());
        Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        //正常消费
         channel.basicAck(deliveryTag,false);

        //nack 丢回队列 最后一个参数设置为true  直接丢弃设置为false  不再重新投递 requeue=false
        // channel.basicNack(deliveryTag,false,false);

    }

    /**
     * 方法二(公司里在用这种):
     */
/*    @RabbitListener(queues = "queue002")
    public void getJson(JSONObject jsonObject, org.springframework.amqp.core.Message message,Channel channel) throws IOException {
        System.out.println("接收到: "+jsonObject.toString());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,true);
    }*/


    /**
     *同事监听同一个队列 就抢着消费 但是消费的总数不会变
     */
    @RabbitListener(queues = "queue002")
    public void getString1(String str, org.springframework.amqp.core.Message message,Channel channel) throws IOException {
        System.out.println("1-----接收到: "+str);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,true);
    }

    @RabbitListener(queues = "queue002")
    public void getString2(String str, org.springframework.amqp.core.Message message,Channel channel) throws IOException {
        System.out.println("2-----接收到: "+str);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,true);
    }


    @RabbitListener(queues = "queue002")
    public void getString3(String str, org.springframework.amqp.core.Message message,Channel channel) throws IOException {
        System.out.println("3-----接收到: "+str);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,true);
    }

    
}
